<template>
  <div class="paper-submission-container">
    <h1>{{ isEditMode ? '编辑论文' : '论文提交' }}</h1>
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="150px"
        label-position="top"
        class="paper-form"
    >
      <!-- 论文基本信息 -->
      <el-card shadow="hover" class="form-section">
        <template #header>
          <div class="card-header">
            <span>论文基本信息</span>
            <el-tag v-if="isEditMode && form.status !== undefined" type="info" style="margin-left: 10px">
              {{ form.status === 0 ? '草稿' : form.status === 1 ? '已提交' : '已审核' }}
            </el-tag>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="论文标题" prop="paperTitle">
              <el-input
                  v-model="form.paperTitle"
                  placeholder="请输入论文标题"
                  clearable
                  :disabled="form.status === 2"
                  @input="handleTitleChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期刊名称" prop="journal">
              <el-input
                  v-model="form.journal"
                  placeholder="请输入期刊名称"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="卷号" prop="volume">
              <el-input
                  v-model="form.volume"
                  placeholder="卷号"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="期号" prop="issue">
              <el-input
                  v-model="form.issue"
                  placeholder="期号"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页码范围" prop="pageRange">
              <el-input
                  v-model="form.pageRange"
                  placeholder="格式: 起始页-结束页"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="检索级别" prop="indexLevel">
              <el-select
                  v-model="form.indexLevel"
                  placeholder="请选择检索级别"
                  clearable
                  :disabled="form.status === 2"
              >
                <el-option label="SCI" value="SCI" />
                <el-option label="SSCI" value="SSCI" />
                <el-option label="EI" value="EI" />
                <el-option label="核心期刊" value="核心" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="影响因子" prop="impactFactor">
              <el-input-number
                  v-model="form.impactFactor"
                  :min="0"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发表日期" prop="publishDate">
              <el-date-picker
                  v-model="form.publishDate"
                  type="date"
                  placeholder="选择发表日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledDate"
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="论文链接/DOI" prop="paperLink">
          <el-input
              v-model="form.paperLink"
              placeholder="请输入论文链接或DOI"
              clearable
              :disabled="form.status === 2"
          />
        </el-form-item>
      </el-card>

      <!-- 作者信息 -->
      <el-card shadow="hover" class="form-section">
        <template #header>
          <div class="card-header">
            <span>作者信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="第一作者" prop="firstAuthor">
              <el-input
                  v-model="form.firstAuthor"
                  placeholder="第一作者姓名"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯作者" prop="correspondingAuthor">
              <el-input
                  v-model="form.correspondingAuthor"
                  placeholder="通讯作者姓名"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="作者名单" prop="authors">
          <el-button
              type="primary"
              @click="addAuthor"
              icon="el-icon-plus"
              :disabled="form.status === 2"
          >
            添加作者
          </el-button>

          <transition-group name="author-list" tag="div">
            <div
                v-for="(author, index) in form.authors"
                :key="index"
                class="author-item"
            >
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-input
                      v-model="author.name"
                      placeholder="作者姓名"
                      :disabled="form.status === 2"
                  />
                </el-col>
                <el-col :span="6">
                  <el-input
                      v-model="author.affiliation"
                      placeholder="所属单位"
                      :disabled="form.status === 2"
                  />
                </el-col>
                <el-col :span="4">
                  <el-select
                      v-model="author.order"
                      placeholder="顺序"
                      :disabled="form.status === 2"
                  >
                    <el-option
                        v-for="n in 10"
                        :key="n"
                        :label="n"
                        :value="n"
                    />
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      @click="removeAuthor(index)"
                      :disabled="form.status === 2"
                  />
                </el-col>
              </el-row>
            </div>
          </transition-group>
        </el-form-item>
      </el-card>

      <div class="form-actions">
        <el-button
            v-if="form.status !== 2"
            type="primary"
            @click="submitForm('draft')"
            :loading="loading"
        >
          {{ isEditMode ? '更新草稿' : '保存草稿' }}
        </el-button>
        <el-button
            v-if="form.status !== 2"
            type="success"
            @click="submitForm('submit')"
            :loading="loading"
        >
          {{ isEditMode ? '提交更新' : '提交审核' }}
        </el-button>
        <el-button
            @click="resetForm"
            :disabled="form.status === 2"
        >
          重置
        </el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue';
import {ElMessage} from 'element-plus';
import {useRoute, useRouter} from 'vue-router';
import paperApi from '@/api/paper.js';
import {useAuthStore} from '@/stores/auth.js';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const formRef = ref(null);

const loading = ref(false);
const isEditMode = ref(false);
const currentPaperId = ref(null);

// 使用计算属性获取用户ID
const userId = computed(() => authStore.user?.userId);

// 表单数据（submitUserId 初始化为 null，后续动态更新）
const form = reactive({
  paperTitle: '',
  journal: '',
  issue: '',
  volume: '',
  pageRange: '',
  indexLevel: '',
  authors: [],
  firstAuthor: '',
  correspondingAuthor: '',
  publishDate: '',
  impactFactor: 0,
  paperLink: '',
  status: 0,
  submitUserId: null
});

// 表单验证规则
const rules = reactive({
  paperTitle: [
    {required: true, message: '论文标题不能为空', trigger: 'blur'},
    {max: 500, message: '论文标题长度不能超过500字符', trigger: 'blur'}
  ],
  journal: [
    {required: true, message: '期刊名称不能为空', trigger: 'blur'},
    {max: 200, message: '期刊名称长度不能超过200字符', trigger: 'blur'}
  ],
  firstAuthor: [
    {required: true, message: '第一作者不能为空', trigger: 'blur'},
    {max: 100, message: '第一作者名称长度不能超过100字符', trigger: 'blur'}
  ],
  publishDate: [
    {required: true, message: '发表日期不能为空', trigger: 'change'}
  ],
  authors: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('至少需要添加一位作者'));
          return;
        }

        const invalidAuthors = value.filter(author =>
            !author.name || !author.name.trim() || author.order === undefined
        );

        if (invalidAuthors.length > 0) {
          callback(new Error('所有作者必须填写姓名和顺序'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 监控标题变化
const handleTitleChange = (value) => {
  form.paperTitle = value;
};

// 初始化表单数据
const initFormData = async () => {
  // 无论是否编辑模式都设置用户ID
  form.submitUserId = userId.value;

  if (route.params.id) {
    try {
      loading.value = true;
      isEditMode.value = true;
      currentPaperId.value = Number(route.params.id);

      const response = await paperApi.getPaperDetails(currentPaperId.value);
      const paperData = response.data;

      // 使用展开运算符避免响应式引用
      form.authors = paperData.authors ? [...paperData.authors] : [];
      form.paperTitle = paperData.paperTitle || '';
      form.journal = paperData.journal || '';
      form.issue = paperData.issue || '';
      form.volume = paperData.volume || '';
      form.pageRange = paperData.pageRange || '';
      form.indexLevel = paperData.indexLevel || '';
      form.firstAuthor = paperData.firstAuthor || '';
      form.correspondingAuthor = paperData.correspondingAuthor || '';
      form.publishDate = paperData.publishDate || '';
      form.impactFactor = paperData.impactFactor || 0;
      form.paperLink = paperData.paperLink || '';
      form.status = paperData.status || 0;

      // 确保作者顺序正确
      form.authors.forEach((author, index) => {
        author.order = author.order || index + 1;
      });

    } catch (error) {
      console.error('获取论文详情失败:', error);
      ElMessage.error(error.message || '获取论文详情失败');
      router.push({name: 'PaperList'});
    } finally {
      loading.value = false;
    }
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  form.authors = [];
  form.paperTitle = '';
  form.journal = '';
  form.issue = '';
  form.volume = '';
  form.pageRange = '';
  form.indexLevel = '';
  form.firstAuthor = '';
  form.correspondingAuthor = '';
  form.publishDate = '';
  form.impactFactor = 0;
  form.paperLink = '';
  form.status = 0;
  form.submitUserId = userId.value; // 重置时重新设置用户ID
};

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

// 添加作者
const addAuthor = () => {
  form.authors.push({
    name: '',
    affiliation: '',
    order: form.authors.length + 1
  });
};

// 删除作者
const removeAuthor = (index) => {
  form.authors.splice(index, 1);
  // 重新排序所有作者
  form.authors.forEach((author, idx) => {
    author.order = idx + 1;
  });
};

// 准备提交数据（返回纯JS对象）
const prepareSubmitData = (action) => {
  if (!authStore.isAuthenticated || !userId.value) {
    throw new Error('用户未登录或会话已过期');
  }

  return {
    paperTitle: form.paperTitle.trim(),
    journal: form.journal.trim(),
    issue: form.issue?.trim() || null,
    volume: form.volume?.trim() || null,
    pageRange: form.pageRange?.trim() || null,
    indexLevel: form.indexLevel || null,
    authors: form.authors.map((author, index) => ({
      name: author.name.trim(),
      affiliation: author.affiliation?.trim() || null,
      order: index + 1
    })),
    firstAuthor: form.firstAuthor.trim(),
    correspondingAuthor: form.correspondingAuthor?.trim() || null,
    publishDate: form.publishDate || null,
    impactFactor: Number(form.impactFactor) || 0,
    paperLink: form.paperLink?.trim() || null,
    status: action === 'submit' ? 1 : 0,
    submitUserId: userId.value // 直接使用计算属性的值
  };
};

// 提交表单
const submitForm = async (action) => {
  try {
    await formRef.value.validate();
    loading.value = true;

    const formData = prepareSubmitData(action);
    console.log('提交数据:', formData);

    const response = isEditMode.value
        ? await paperApi.updatePaper(currentPaperId.value, formData)
        : await paperApi.submitPaper(formData);

    ElMessage.success(response.data.message || (isEditMode.value ? '论文更新成功' : '论文提交成功'));
    router.push({name: 'StudentPaperManagement'});

  } catch (error) {
    console.error('提交失败:', error);
    let errorMessage = '操作失败，请重试';

    if (error.response) {
      if (error.response.status === 400) {
        errorMessage = typeof error.response.data === 'string'
            ? error.response.data
            : error.response.data.message || errorMessage;
      } else if (error.response.status === 401) {
        errorMessage = '登录已过期，请重新登录';
      } else if (error.response.status === 403) {
        errorMessage = '没有操作权限';
      }
    } else if (error.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 返回
const goBack = () => {
  router.push({name: 'PaperList'});
};

onMounted(() => {
  initFormData();
});
</script>

<style scoped>
.paper-submission-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.paper-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.author-item {
  margin-top: 10px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.author-list-enter-active,
.author-list-leave-active {
  transition: all 0.3s ease;
}

.author-list-enter-from,
.author-list-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>